#include "pcap_utils.h"
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>

int main() {
    // 测试数据
    uint8_t src_mac[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55};
    uint8_t dst_mac[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
    uint32_t src_ip = inet_addr("192.168.1.100");
    uint32_t dst_ip = inet_addr("192.168.1.200");
    uint16_t src_port = 12345;
    uint16_t dst_port = 80;
    uint8_t payload[] = "Hello, this is a test packet!1234567";
    uint16_t payload_length = sizeof(payload) - 1;

    // 1. 测试内存缓冲区方式
    printf("=== Testing Buffer Method ===\n");
    uint8_t *buffer = (uint8_t *)malloc(65535);
    uint32_t total_length = 0;

    // 写入PCAP全局头
    total_length = write_pcap_global_header_to_buffer(buffer);

    // 写入UDP包
    total_length += write_udp_packet_to_buffer(buffer + total_length,
                                               src_mac, dst_mac,
                                               src_ip, dst_ip,
                                               src_port, dst_port,
                                               payload, payload_length);

    printf("Total buffer length: %u bytes\n", total_length);

    // 解析buffer中的数据
    printf("\nParsing buffer content:\n");
    parse_pcap_buffer(buffer, total_length);

    // 2. 测试文件方式
    printf("\n=== Testing File Method ===\n");
    FILE *fp = fopen("test_output.pcap", "wb");
    if (!fp) {
        printf("Failed to create file\n");
        free(buffer);
        return 1;
    }

    // 写入PCAP全局头
    write_pcap_global_header_to_file(fp);

    // 写入UDP包
    write_udp_packet_to_file(fp,
                             src_mac, dst_mac,
                             src_ip, dst_ip,
                             src_port, dst_port,
                             payload, payload_length);

    fclose(fp);
    printf("PCAP file created: test_output.pcap\n");

    // 读取并解析刚创建的文件
    printf("\nReading and parsing the created file:\n");
    fp = fopen("test_output.pcap", "rb");
    if (fp) {
        // 获取文件大小
        fseek(fp, 0, SEEK_END);
        long file_size = ftell(fp);
        fseek(fp, 0, SEEK_SET);

        // 读取文件内容到buffer
        uint8_t *file_buffer = (uint8_t *)malloc(file_size);
        fread(file_buffer, 1, file_size, fp);
        fclose(fp);

        // 解析文件内容
        parse_pcap_buffer(file_buffer, file_size);

        free(file_buffer);
    }

    free(buffer);
    printf("\nTest completed!\n");

    return 0;
}